package com.web.tasks;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.web.common.Sys;
import com.web.model.TCathectic;
import com.web.model.TUser;
import com.web.model.TUserBalanceRecord;
import com.web.model.TWinNum;
import com.web.model.TWinResult;
import com.web.model.constant.Constant;
import com.web.service.TCathecticService;
import com.web.service.TUserBalanceRecordService;
import com.web.service.TUserService;
import com.web.service.TWinNumService;
import com.web.service.TWinResultService;
import com.web.utils.HttpRequest;
import com.web.utils.HttpTest;
import com.web.utils.WinNumUtil;

import javax.annotation.PostConstruct;

/**
 * 定期获取开奖结果
 * 部署safe的时候注释掉类上面的@component注解，避免冲突
 *
 * @author wzy
 */
@Component
public class RefreshWinNumTask extends AbstractTask {

    @Autowired
    private TUserService userService;

    @Autowired
    private TWinNumService winNumService;

    @Autowired
    private TWinResultService winResultService;

    @Autowired
    private TCathecticService cathecticService;

    @Autowired
    private TUserBalanceRecordService userBalanceRecordService;

    @Resource(name = "sys")
    private Sys sys;

    @Resource(name = "winNumUtil")
    private WinNumUtil winNumUtil;

    private String jsonResult;


    private JSONObject jsonObject;
    private Set<String> keySet = new HashSet<String>();
    private TWinNum insertWinNum = new TWinNum();
    private TWinNum resultWinNum;
    private String nums;
    private String[] numArr;
    private long nextTime;
    private Long termcd;
    private static Long maxTerm = 0l;
    private Calendar cal;
    private Map<String, Object> param = new HashMap<String, Object>();

    private List<TCathectic> cathecticList;
    private TWinResult insertWinResult = new TWinResult();
    //private TUserBalanceRecord userBalanceRecord = new TUserBalanceRecord();
    private List<TWinResult> winResultList;
    private TUser user;
    private TUser up;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    protected RefreshWinNumTask() {
        super("获取开奖结果", true);
    }

    //0 */1 * * * ?  测试环境使用
    //0/4 * * * * ?  生产使用
    @Override
    @Scheduled(cron = "0/4 * * * * ?")
    public void taskEntrance() {
        super.taskEntrance();
    }

    @Override
    protected void executeTask() {
//		if(isInit){
//			logger.info("init方法执行ing");
//			return;
//		}
        cal = Calendar.getInstance();
        int currH = cal.get(Calendar.HOUR_OF_DAY);
        if (currH >= 0 && currH < 9) { //没结果时间段
            logger.info("休息时段，不请求结果");
            return;
        }
        long now = System.currentTimeMillis();
        if (now <= nextTime) {//三分钟之内不请求
            logger.info("三分钟之内不请求");
            return;
        }
        logger.info("================ 获取开奖结果 ==================");
        //开采网
        jsonResult = HttpRequest.get(HttpRequest.pkUrl, HttpRequest.charset);
        //彩票控
        if (jsonResult == null) {
            jsonResult = HttpTest.get(HttpTest.pkUrl, HttpTest.charset);
        }
        if (jsonResult != null) {
            checkResult(jsonResult);
        }
    }

    /*彩票控的接口*/
    private void checkResult(String jsonResult) {
        try {
            logger.info("jsonResult : " + jsonResult);
            jsonObject = JSONObject.parseObject(jsonResult);// 转化为JSON类
            keySet = jsonObject.keySet();
            for (String key : keySet) {
                termcd = Long.valueOf(key);
                logger.info("termcd:" + termcd + "---maxTermcd: " + maxTerm);
                if (termcd > maxTerm) {
                    logger.info("开始处理开奖结果");
                    maxTerm = termcd;
                    sys.setLastTermcd(termcd);

                    cal = Calendar.getInstance();
                    insertWinNum(jsonObject.getJSONObject(key), termcd);// 先入库
                    winNumUtil.checkWinNum(insertWinNum, numArr);

                    Date winTime = sdf.parse(jsonObject.getJSONObject(key).getString("dateline"));
                    cal.setTime(winTime);
                    cal.add(Calendar.MINUTE, 3);
                    nextTime = cal.getTimeInMillis();

                    sys.setLastWinNum(insertWinNum);//设置最后一次开奖数据
                    sys.setTime(winTime);

                    break;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    @PostConstruct
    public void init() throws ParseException { // 定时器默认开始加载的时候先获取默认10期入库，同时获取出最大期数
        logger.info("加载默认开奖数据");
        jsonResult = HttpTest.get(HttpTest.pkUrl, HttpTest.charset);
        jsonObject = JSONObject.parseObject(jsonResult);// 转化为JSON类
        keySet = jsonObject.keySet();
        for (String key : keySet) {
            termcd = Long.valueOf(key);
            logger.info("termcd:" + termcd + "---maxTermcd:" + maxTerm);
            if (termcd > maxTerm) {//设置最后一期开奖期数和封盘时间
                logger.info("开始处理数据");
                maxTerm = termcd;
                sys.setTime(sdf.parse(jsonObject.getJSONObject(key).getString("dateline")));
                sys.setLastTermcd(termcd);
                processCathectic(termcd);
                insertWinNum(jsonObject.getJSONObject(key), Long.valueOf(termcd));
                processResult();//计算开奖结果
                prossFirstAndSecond();
                sys.setLastWinNum(insertWinNum);//设置最后一次开奖数据
            }
            resultWinNum = winNumService.selectByPrimaryKey(termcd);
            if (resultWinNum == null) {

            }
            processCathectic(termcd);//执行开奖结果计算
        }
    }

    private void insertWinNum(JSONObject jsonObj, long termcd) {
        try {
            //插库
            nums = jsonObj.getString("number");
            numArr = nums.split(",");
            insertWinNum.setNum1(numArr[0]);
            insertWinNum.setNum2(numArr[1]);
            insertWinNum.setNum3(numArr[2]);
            insertWinNum.setNum4(numArr[3]);
            insertWinNum.setNum5(numArr[4]);
            insertWinNum.setNum6(numArr[5]);
            insertWinNum.setNum7(numArr[6]);
            insertWinNum.setNum8(numArr[7]);
            insertWinNum.setNum9(numArr[8]);
            insertWinNum.setNum10(numArr[9]);
            insertWinNum.setWinTime(sdf.parse(jsonObj.getString("dateline")));
            insertWinNum.setTermCd(termcd);
            resultWinNum = winNumService.selectByPrimaryKey(termcd);
            if (resultWinNum == null) {
                winNumService.insert(insertWinNum);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理开奖结果
     */
    private void processResult() {
        param.clear();
        param.put("winTypeWay", 1);
        param.put("sort", "win_type_code");

        insertWinResult.setTermCd(insertWinNum.getTermCd() + "");
        for (int i = 0; i < numArr.length; i++) { //处理1-10名
            insertWinResult.setDictType(checkDictType(i));

            insertWinResult.setDictCode(numArr[i]);
            winResultService.insert(insertWinResult);//号码

            insertWinResult.setDictCode(checkBigOrSmall(numArr[i]));
            winResultService.insert(insertWinResult);//大小

            insertWinResult.setDictCode(checkDoubleOrSingle(numArr[i]));
            winResultService.insert(insertWinResult);//单双
            if (i < 5) {
                insertWinResult.setDictCode(checkDragonOrTiger(numArr[i], numArr[numArr.length - i - 1]));
                winResultService.insert(insertWinResult);//龙虎
            }
        }
    }

    private void prossFirstAndSecond() {
        int firstAndSecond = (Integer.parseInt(numArr[0]) + Integer.parseInt(numArr[1]));//冠亚和值
        insertWinResult.setDictType("11");
        insertWinResult.setDictCode(firstAndSecond + "");
        winResultService.insert(insertWinResult);//冠亚和

        int bigOrSmall = 21; //小
        if (firstAndSecond > 11) {//大
            bigOrSmall = 20;
        }
        insertWinResult.setDictCode(bigOrSmall + "");
        winResultService.insert(insertWinResult);//冠亚和大小

        int doubleOrSingle = 22;//单
        if (firstAndSecond % 2 == 0) {
            doubleOrSingle = 23;
        }
        insertWinResult.setDictCode(doubleOrSingle + "");
        winResultService.insert(insertWinResult);//冠亚和单双

    }

    private String checkBigOrSmall(String numStr) {
        String result = "14";
        int num = Integer.parseInt(numStr);
        if (num >= 6) {
            result = "13";
        }
        return result;
    }

    private String checkDoubleOrSingle(String numStr) {
        String result = "11";
        int num = Integer.parseInt(numStr);
        if (num % 2 == 0) {
            result = "12";
        }
        return result;
    }

    private String checkDragonOrTiger(String numStr1, String numStr2) {
        String result = "16";
        int num1 = Integer.parseInt(numStr1);
        int num2 = Integer.parseInt(numStr2);
        if (num1 > num2) {
            result = "15";
        }
        return result;
    }

    private String checkDictType(int i) {
        String dictType = "";
        switch (i) {
            case 0:
                dictType = "01";
                break;
            case 1:
                dictType = "02";
                break;
            case 2:
                dictType = "03";
                break;
            case 3:
                dictType = "04";
                break;
            case 4:
                dictType = "05";
                break;
            case 5:
                dictType = "06";
                break;
            case 6:
                dictType = "07";
                break;
            case 7:
                dictType = "08";
                break;
            case 8:
                dictType = "09";
                break;
            case 9:
                dictType = "10";
                break;
            default:
                dictType = "11";
                break;
        }
        return dictType;
    }

    private void processCathectic(Long checktermCd) {
        logger.info("processCathectic start ");
//		checktermCd = 588843l;
        Date now = new Date();
        param.clear();
        param.put("termCd", checktermCd);
        param.put("isWin", "0");
        cathecticList = cathecticService.selectList(param); //当期订单列表
        winResultList = winResultService.selectList(param); //当期开奖结果

        TUserBalanceRecord userBalanceRecord = null;
        TCathectic c = null;
        for (TWinResult r : winResultList) {
            userBalanceRecord = new TUserBalanceRecord();
            for (int i = 0; i < cathecticList.size(); i++) {
                c = cathecticList.get(i);
                if (r.getDictType().equals(c.getCathecticType()) && r.getDictCode().equals(c.getCathecticCode())) {
                    logger.info("type:" + r.getDictType() + "-code:" + r.getDictCode() + "--amt:" + c.getWinAmt());
                    /****修改订单表状态为赢****/
                    c.setIsWin("1");
                    cathecticService.updateByPrimaryKey(c); //修改下单表
                    /*******增加资金记录*************/
                    userBalanceRecord.setBalance(c.getWinAmt());
                    userBalanceRecord.setUserId(c.getCreateUser());
                    userBalanceRecord.setBalanceContext(sys.getOpenBalanceContext(0, checktermCd, c.getCathecticType(), c.getCathecticCode()));
                    userBalanceRecord.setBalanceDate(now);
                    userBalanceRecord.setBalanceType(Constant.USER_BALANCE_TYPE_3);
                    userBalanceRecordService.insert(userBalanceRecord);
                    /********更改用户余额**************/
                    user = userService.selectByPrimaryKey(c.getCreateUser());
                    up = new TUser();
                    up.setUserBalance(user.getUserBalance() + c.getWinAmt());
                    up.setUserId(user.getUserId());
                    userService.updateByPrimaryKey(up);
                }
            }
            /**********处理输掉的订单***************/
            cathecticService.updateLoseCathectic(termcd);
        }
        logger.info("processCathectic end");
    }
}
